package com.zidongxiangxi.sharding.job.core.listener;

import com.alibaba.fastjson.JSON;
import com.zidongxiangxi.sharding.job.core.ShardingJob;
import com.zidongxiangxi.sharding.job.core.ShardingJobConfig;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;

/**
 * 配置变更监听
 *
 * @author chenxudong
 * @date 2021/02/18
 */
public class ConfigNodeChangeListener extends AbstractNodeChangeListener {
    private final ShardingJob shardingJob;

    public ConfigNodeChangeListener(final ShardingJob shardingJob) {
        this.shardingJob = shardingJob;
    }

    @Override
    public boolean canHandleChange(String path, Type eventType) {
        return !shardingJob.isShutdown()
            && shardingJob.getConfigNode().isConfigPath(path)
            && Type.NODE_UPDATED == eventType;
    }

    @Override
    void dealDataChange(String path, Type eventType, String data) {
        ShardingJobConfig config = JSON.parseObject(data, ShardingJobConfig.class);
        shardingJob.setConfig(config);
    }
}
